#include <iostream>
#include <cerrno>
#include <string>
#include "Socket.hpp"
#include "Protocol.hpp"

using namespace ns_protocol;

static void Usage(const char *str)
{
    std::cout << "\n Usage:" << str << " ip port\n"
              << std::endl;
}

// ./ CalClient ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    Sock sock;
    int sockfd = sock.Socket();
    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);
    if (sock.Connect(sockfd, server_ip, server_port) == false)
    {
        std::cout << "connect error" << std::endl;
        exit(1);
    }
    std::cout << "任务格式：\na + b" << std::endl;
    // 客户端执行
    while (true)
    {
        std::cout << "请输入任务：" << std::endl;
        // 输入请求
        Request req;
        std::cin >>  req._x >> req._op >> req._y;
        // 序列化
        std::string str = req.Serialize();
        // std::string str;
        // std::getline(std::cin, str);
        if (str.empty())
            continue;
        // 添加报头
        std::string send_message = Encode(str);

        // 发送
        ssize_t sz = send(sockfd, send_message.c_str(), send_message.size(), 0);
        if (sz <= 0)
        {
            std::cout << "send error:" << errno << " " << strerror(errno) << std::endl;
            exit(3);
        }
        // 接收
        char buffer[1024];
        std::string message;
        while (true)
        {
            sz = recv(sockfd, buffer, sizeof(buffer) - 1, 0);
            if (sz > 0)
            {
                buffer[sz] = 0;
            }
            else if (sz == 0)
            {
                std::cout << "服务器关闭了" << std::endl;
                exit(1);
            }
            else
            {
                std::cout << "recv error:" << errno << " " << strerror(errno) << std::endl;
                exit(2);
            }
            // 剪去报头
            std::string recv_str = buffer;
            message = Decode(recv_str);
            if (!message.empty())
                break;
        }

        // 反序列化
        Response res;
        res.Deserialize(message);
        std::cout << res._x << " " << res._op << " " << res._y;

        // 结果展示
        if (res._status == 0)
        {
            std::cout << " = " << res._result << std::endl;
        }
        else
        {
            std::cout << res.error() << std::endl;
        }
        // sleep(1);
    }

    return 0;
}